<template>
  <div class="app-container">


    <el-table  :data="budgetList" border style="margin-top: 20px;"
     :span-method="spanBudgetSubject"
     :row-class-name="tableRowClassName">
       <!-- 预算科目层级 -->
      <el-table-column label="预算科目名称" align="center">
        <el-table-column label="一级预算科目名称" align="center" prop="subjectLevel1" />
        <el-table-column label="二级预算科目名称" align="center" prop="subjectLevel2" />
        <el-table-column label="三级预算科目名称" align="center" prop="subjectLevel3" />
        <el-table-column label="四级预算科目名称" align="center" prop="subjectLevel4" />
      </el-table-column>

      <!-- 财政专项资金列（可编辑） -->
      <el-table-column label="财政专项资金批准数" align="center">
        <!-- 自治区专项资金 -->
        <el-table-column label="自治区专项资金(万元)" align="center" prop="provincialFund">
          <template slot-scope="scope">
            <div v-if="!scope.row.isTotalRow">
              <div v-if="!viewFlag">
                <el-input
                  v-model.number="scope.row.provincialFund"
                  type="number"

                  @input="handleAmountChange"
                />
              </div>
              <div v-else style="font-weight: bold;">
                {{ scope.row.provincialFund }}
              </div>
            </div>
            <div v-else style="font-weight: bold;">
              {{ scope.row.provincialFund }}
            </div>
          </template>
        </el-table-column>

        <!-- 市级配套资金 -->
        <el-table-column label="市级配套的资金(万元)" align="center" prop="municipalFund">
          <template slot-scope="scope">
            <div v-if="!scope.row.isTotalRow">
              <div v-if="!viewFlag">
                <el-input
                  v-model.number="scope.row.municipalFund"
                  type="number"

                  @input="handleAmountChange"
                />
              </div>
              <div v-else style="font-weight: bold;">
                {{ scope.row.municipalFund }}
              </div>
            </div>
            <div v-else style="font-weight: bold;">
              {{ scope.row.municipalFund }}
            </div>
          </template>
        </el-table-column>
      </el-table-column>

      <!-- 自筹资金列（可编辑） -->
      <el-table-column label="自筹资金批准数(万元)" align="center" prop="selfRaisedFund">
        <template slot-scope="scope">
          <div v-if="!scope.row.isTotalRow">
             <div v-if="!viewFlag">
              <el-input
                v-model.number="scope.row.selfRaisedFund"
                type="number"

                @input="handleAmountChange"
              />
            </div>
            <div v-else style="font-weight: bold;">
              {{ scope.row.selfRaisedFund }}
            </div>
          </div>
          <div v-else style="font-weight: bold;">
            {{ scope.row.selfRaisedFund }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="小计(万元)" align="center" prop="total">
        <template slot-scope="scope">
          <div style="font-weight: bold;">{{ scope.row.total }}</div>
        </template>
      </el-table-column>

      <!-- 备注列（可编辑） -->
      <el-table-column label="备注" align="center" prop="remark">
        <template slot-scope="scope">
          <div v-if="!viewFlag">
            <el-input v-model="scope.row.remark"  />
          </div>
          <div v-else style="font-weight: bold;">
            {{ scope.row.remark }}
          </div>
        </template>
      </el-table-column>

    </el-table>




  </div>
</template>

<script>
import { listBudget } from "@/api/sci/budget";

export default {
  name: "Budget",
   props: {
    projectId: {
      type: [String, Number],
      default: null
    },
    viewFlag: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目预算表格数据
      budgetList : [],

      totalProvincial: 0, // 自治区专项资金总和
      totalMunicipal: 0, // 市级配套资金总和
      totalSelfRaised: 0, // 自筹资金总和

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: this.projectId,
      },
      // 表单参数
      form: {
        projectId: this.projectId,
      },
      // 表单校验
      rules: {
        subjectLevel1: [
          { required: true, message: "一级预算科目名称不能为空", trigger: "blur" }
        ],
        provincialFund: [
          { required: true, message: "自治区专项资金(万元)不能为空", trigger: "blur" }
        ],
        municipalFund: [
          { required: true, message: "市级配套资金(万元)不能为空", trigger: "blur" }
        ],
        selfRaisedFund: [
          { required: true, message: "自筹资金批准数(万元)不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    // this.initBudgetList();
    if(this.projectId!== null){
      this.getList();
    }else{
      this.initBudgetList();
      this.loading=false;
    }
  },
  watch: {
    projectId(newVal) {
      // 当 projectId 变化时，更新查询参数并重新获取列表
      if (newVal === null) {
        this.initBudgetList();
        this.loading=false;
        return;
      }
      this.queryParams.projectId = newVal;
      this.getList();
    }
  },
  computed: {
    totalRow() {
      return {
        subjectLevel1: '总计',
        provincialFund: this.totalProvincial.toFixed(2),
        municipalFund: this.totalMunicipal.toFixed(2),
        selfRaisedFund: this.totalSelfRaised.toFixed(2)
      };
    }
  },
  methods: {
     // 返回所有数据
    getBudgetList() {
      return this.budgetList;
    },

    // 只返回普通行数据（不包含总计行）
    getNormalBudgetList() {
      return this.budgetList.filter(item => !item.isTotalRow);
    },
    initBudgetList() {
      this.budgetList = [
        {
          isTotalRow: false,
          subjectLevel1: '直接费用',
          subjectLevel2: '设备费',
          subjectLevel3: '设备购置费',
          subjectLevel4: '50万元以下设备',
          provincialFund: '',
          municipalFund: '',
          selfRaisedFund: '',
          remark: '',
          total: 0
        },
        {
          isTotalRow: false,
          subjectLevel1: '直接费用',
          subjectLevel2: '设备费',
          subjectLevel3: '设备购置费',
          subjectLevel4: '50万元以上设备',
          provincialFund: '',
          municipalFund: '',
          selfRaisedFund: '',
          remark: '',
          total: 0
        },
        {
          isTotalRow: false,
          subjectLevel1: '直接费用',
          subjectLevel2: '业务费',
          subjectLevel3: '',
          subjectLevel4: '',
          provincialFund: '',
          municipalFund: '',
          selfRaisedFund: '',
          remark: '',
          total: 0
        },
        {
          isTotalRow: false,
          subjectLevel1: '直接费用',
          subjectLevel2: '劳务费',
          subjectLevel3: '',
          subjectLevel4: '',
          provincialFund: '',
          municipalFund: '',
          selfRaisedFund: '',
          remark: '',
          total: 0
        },
        {
          isTotalRow: false,
          subjectLevel1: '间接费用',
          subjectLevel2: '',
          subjectLevel3: '',
          subjectLevel4: '',
          provincialFund: '',
          municipalFund: '',
          selfRaisedFund: '',
          remark: '',
          total: 0
        },


        // 添加总计行占位符（标记为 isTotalRow: true）
        {
          isTotalRow: true,
          type: 'direct',
          subjectLevel1: '直接费用总和',

          provincialFund: 0,
          municipalFund: 0,
          selfRaisedFund: 0,
          remark: '',
          total: 0
        },
        {
          isTotalRow: true,
          type: 'indirect',
          subjectLevel1: '间接费用总和',

          provincialFund: 0,
          municipalFund: 0,
          selfRaisedFund: 0,
          remark: '',
          total: 0
        },
        {
          isTotalRow: true,
          type: 'all',
          subjectLevel1: '所有费用总和',

          provincialFund: 0,
          municipalFund: 0,
          selfRaisedFund: 0,
          total: 0,
          remark: ''
        }
      ];
    },

    handleAmountChange() {
      // 更新每行的小计
      this.budgetList.forEach(item => {
        if (!item.isTotalRow) {
          const p = parseFloat(item.provincialFund) || 0;
          const m = parseFloat(item.municipalFund) || 0;
          const s = parseFloat(item.selfRaisedFund) || 0;
          item.total = (p + m + s).toFixed(2);
        }
      });
       this.calculateTotals(); // 每次输入金额都触发计算
    },

    /** 查询项目预算列表 */
    getList() {
      this.loading = true;
      listBudget(this.queryParams).then(response => {
        const normalData = response.rows || [];

        // 补充普通行字段
        this.budgetList = normalData.map(item => ({
          ...item,
          isTotalRow: false, // 标记为普通行
          total: (parseFloat(item.provincialFund) || 0) +
                (parseFloat(item.municipalFund) || 0) +
                (parseFloat(item.selfRaisedFund) || 0)
        }));

        // 添加总计行（初始化字段）
        this.budgetList.push(
          {
            isTotalRow: true,
            type: 'direct',
            subjectLevel1: '直接费用总和',
            provincialFund: 0,
            municipalFund: 0,
            selfRaisedFund: 0,
            total: 0
          },
          {
            isTotalRow: true,
            type: 'indirect',
            subjectLevel1: '间接费用总和',
            provincialFund: 0,
            municipalFund: 0,
            selfRaisedFund: 0,
            total: 0
          },
          {
            isTotalRow: true,
            type: 'all',
            subjectLevel1: '所有费用总和',
            provincialFund: 0,
            municipalFund: 0,
            selfRaisedFund: 0,
            total: 0
          }
        );

        // 触发计算
        this.calculateTotals();

        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        this.$message.error('加载预算数据失败');
        console.error('请求失败:', error);
        this.loading = false;
      });
    },

    spanBudgetSubject({ row, column, rowIndex, columnIndex }) {
      if (row.isTotalRow) {
        // 总计行：只让“预算科目名称”列显示，其它列隐藏
        // 只有第一列（subjectLevel1）显示并合并前四列
        if (columnIndex === 0) {
          return { rowspan: 1, colspan: 4 }; // 合并前四列为“预算科目名称”
        } else if (
          columnIndex === 1 || // subjectLevel2
          columnIndex === 2 || // subjectLevel3
          columnIndex === 3    // subjectLevel4
        ) {
          return { rowspan: 0, colspan: 0 }; // 隐藏这三列
        } else {
          // 其他列正常显示（如财政专项资金、自筹资金、备注等）
          return { rowspan: 1, colspan: 1 };
        }
      }

      // 原始合并逻辑（按一级、二级、三级科目合并）
      const data = this.budgetList;
      if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2) {
        let spanCount = 1;
        while (
          rowIndex + spanCount < data.length &&
          data[rowIndex + spanCount][column.property] === row[column.property]
        ) {
          spanCount++;
        }

        if (
          rowIndex === 0 ||
          (rowIndex > 0 && data[rowIndex - 1][column.property] !== row[column.property])
        ) {
          return { rowspan: spanCount, colspan: 1 };
        } else {
          return { rowspan: 0, colspan: 0 };
        }
      }
    },

    calculateTotals() {
      let directProvincial = 0;
      let directMunicipal = 0;
      let directSelfRaised = 0;

      let indirectProvincial = 0;
      let indirectMunicipal = 0;
      let indirectSelfRaised = 0;

      // 遍历 budgetList，只统计非总计行
      this.budgetList.forEach(item => {
        if (!item.isTotalRow) {
          const p = parseFloat(item.provincialFund) || 0;
          const m = parseFloat(item.municipalFund) || 0;
          const s = parseFloat(item.selfRaisedFund) || 0;

          if (item.subjectLevel1 === '直接费用') {
            directProvincial += p;
            directMunicipal += m;
            directSelfRaised += s;
          } else if (item.subjectLevel1 === '间接费用') {
            indirectProvincial += p;
            indirectMunicipal += m;
            indirectSelfRaised += s;
          }
        }
      });

      const directTotal = directProvincial + directMunicipal + directSelfRaised;
      const indirectTotal = indirectProvincial + indirectMunicipal + indirectSelfRaised;
      const allTotal = directTotal + indirectTotal;

      // 找出总计行并更新它们
      const totalRows = this.budgetList.filter(row => row.isTotalRow);
      if (totalRows.length >= 3) {
        totalRows[0].provincialFund = directProvincial.toFixed(2);
        totalRows[0].municipalFund = directMunicipal.toFixed(2);
        totalRows[0].selfRaisedFund = directSelfRaised.toFixed(2);
        totalRows[0].total = directTotal.toFixed(2);

        totalRows[1].provincialFund = indirectProvincial.toFixed(2);
        totalRows[1].municipalFund = indirectMunicipal.toFixed(2);
        totalRows[1].selfRaisedFund = indirectSelfRaised.toFixed(2);
        totalRows[1].total = indirectTotal.toFixed(2);

        totalRows[2].provincialFund = (directProvincial + indirectProvincial).toFixed(2);
        totalRows[2].municipalFund = (directMunicipal + indirectMunicipal).toFixed(2);
        totalRows[2].selfRaisedFund = (directSelfRaised + indirectSelfRaised).toFixed(2);
        totalRows[2].total = allTotal.toFixed(2);
      }
    },
    tableRowClassName({ row }) {
    if (row.isTotalRow) {
      return 'total-row';
    }
    return '';
  },
  }
};

</script>
<style>
.total-row {
  background-color: #f5f7fa !important;
}
</style>
